﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

namespace MKAdmin.ToolKit
{
    public static class JsonHelper
    {
        /// <summary>
        /// 作者：
        /// 时间：2018.02.08
        /// 描述：对象转为Json字符串
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="dateTimeFormat"></param>
        /// <returns></returns>
        public static string ToJson(this object obj, string dateTimeFormat = "yyyy-MM-dd HH:mm:ss")
        {
            // 空对象返回
            if (null == obj) return string.Empty;

            try
            {
                // 日期时间格式化为空
                if (string.IsNullOrWhiteSpace(dateTimeFormat))
                    return JsonConvert.SerializeObject(obj);

                // 日期时间格式化
                var timeFormat = new IsoDateTimeConverter { DateTimeFormat = dateTimeFormat };
                return JsonConvert.SerializeObject(obj, Formatting.Indented, timeFormat);
            }
            catch (Exception ex)
            {
                throw new Exception("JsonHelper.ToJson()：" + ex.Message);
            }
        }

        /// <summary>
        /// 作者：
        /// 时间：2018.02.08
        /// 描述：Json字符串转为对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="jsonStr"></param>
        /// <returns></returns>
        public static T JsonToObject<T>(this string jsonStr)
        {
            if (string.IsNullOrWhiteSpace(jsonStr))
                return default(T);
            try
            {
                return JsonConvert.DeserializeObject<T>(jsonStr);
            }
            catch (Exception ex)
            {
                throw new Exception("JsonHelper.JsonToObject<T>(): " + ex.Message);
            }
        }

        /// <summary>
        /// java时间戳格式时间戳转为C#格式时间
        /// </summary>
        /// <param name="timeStamp"></param>
        /// <returns></returns>
        public static DateTime GetTime(long timeStamp)
        {
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long lTime = timeStamp * 10000;
            TimeSpan toNow = new TimeSpan(lTime);
            return dtStart.Add(toNow);
        }
    }
}
